<!--
 * @Autor: Ruohong Yu
 * @Date: 2021-11-27 16:40:05
 * @LastEditors: Haiting Zhao
 * @LastEditTime: 2021-12-19 13:18:04
 * @Description: 登录和注册
 * @FilePath: \Management-of-Scientific-Research-in-Universities-Front\src\views\LoginPlus.vue
-->

<template>
  <div class="container">
    <div class="forms-container">
      <div class="signin-signup">
        <form action="" class="sign-in-form">
          <h2 class="title">SICNU</h2>
          <h2 class="title">高校科研系统</h2>
          <div class="input-field">
            <i class="fa fa-user" />
            <input
              v-model="loginForm.username"
              type="text"
              placeholder="Username"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-lock" />
            <input
              v-model="loginForm.password"
              type="password"
              placeholder="Password"
            >
          </div>
          <div class="input-field input-verify">
            <i class="fa fa-lock" />
            <input
              v-model="loginForm.pswverify"
              type="text"
              placeholder="Verify Code"
            >
            <a
              href="javascript:;"
              class="pswverifyimg"
              @click="changeCodeImg()"
            ><img
              :src="pswverifyimg"
            ></a>
          </div>
          <div v-show="loginForm.errorVisible">
            {{ loginForm.errorMsg }}
          </div>

          <el-row :gutter="20">
            <el-col :span="12">
              <input
                type="button"
                value="登 录"
                class="btn solid"
                @click="userpwdLogin"
              >
            </el-col>
            <el-col :span="12">
              <input
                type="button"
                value="忘记密码"
                class="btn solid"
                @click="dialogVisible = true"
              >
            </el-col>
          </el-row>
        </form>
        <form action="" class="sign-up-form">
          <h2 class="title">用户注册</h2>
          <div class="input-field">
            <i class="fa fa-user" />
            <select id="userrole" name="">
              <option value="1">教师</option>
              <option value="2">秘书处</option>
              <option value="3">机构用户</option>
            </select>
          </div>
          <div class="input-field">
            <i class="fa fa-user" />
            <input
              v-model="registerForm.usernumber"
              type="text"
              placeholder="学号/工号"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-user" />
            <input
              v-model="registerForm.username"
              type="text"
              placeholder="用户名"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-envelope" />
            <input
              v-model="registerForm.realname"
              type="text"
              placeholder="真实姓名"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-envelope" />
            <input
              v-model="registerForm.mobile"
              type="text"
              placeholder="手机号"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-envelope" />
            <input
              v-model="registerForm.email"
              type="text"
              placeholder="邮箱"
            >
          </div>
          <div class="input-field">
            <i class="fa fa-lock" />
            <input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
            >
          </div>
          <input
            type="button"
            value="注 册"
            class="btn solid"
            @click="register"
          >
        </form>
      </div>

      <div class="panels-container">
        <div class="panel left-panel">
          <div class="content">
            <h3>新用户注册</h3>
            <p>SICNU软件工程第八组（-。-）</p>
            <button id="sign-up-btn" class="btn transparent">去注册</button>
          </div>

          <img src="../assets/img/log.svg" class="image" alt="">
        </div>

        <div class="panel right-panel">
          <div class="content">
            <h3>已经注册过？</h3>
            <p>快去登录撒</p>
            <button id="sign-in-btn" class="btn transparent">去登陆</button>
          </div>

          <img src="../assets/img/register.svg" class="image" alt="">
        </div>
      </div>
    </div>

    <el-dialog title="找回密码" :visible.sync="dialogVisible" width="50%">
      <!-- <span>支付1元获取密码</span>
      <img src="../assets/img/pay.jpg" style="height: 200px"> -->
      <el-form ref="phoneForm" hide-required-asterisk :model="phoneForm" label-width="70px" class="phonein">
        <el-form-item
          label="手机号"
          prop="phone"
          :rules="[
            { required: true, message: '手机号不能为空'},
          ]"
        >
          <el-input v-model="phoneForm.phone" type="text" style="width:240px;" autocomplete="on" />
          <el-button
            class="verifybtn"
            type="primary"
            :disabled="disabled=!show"
            @click="getVerify"
          >
            <span v-show="show">获取验证码</span>
            <span v-show="!show" class="count">{{ count }} s</span>
          </el-button>
        </el-form-item>
        <el-form-item
          label="验证码"
          prop="phverify"
          :rules="[
            { required: true, message: '验证码不能为空'},
          ]"
        >
          <el-input v-model="phoneForm.phverify" style="width:240px;" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="修改密码"
          prop="psw"
          :rules="[
            { required: true, message: '密码不能为空'},
          ]"
        >
          <el-input v-model="phoneForm.psw" style="width:240px;" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button class="loginbtn" type="primary" @click="retrievePassword('phoneForm')">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import crypto from '../crypto/crypto.js'
export default {
  name: 'Loginplus',
  data() {
    return {
      permissionList: [],
      roleName: '',
      loginForm: {
        username: '',
        password: '',
        pswverify: '',
        errorMsg: '',
        errorVisible: false
      },
      registerForm: {
        username: '',
        realname: '',
        mobile: '',
        email: '',
        password: '',
        roleId: '',
        usernumber: ''
      },
      dialogVisible: false,
      pswverifyimg: '',
      show: true,
      count: '', // 初始化次数
      timer: null,
      phoneForm: {
        phone: '',
        phverify: '',
        psw: ''
      }
    }
  },
  mounted() {
    const sign_in_btn = document.querySelector('#sign-in-btn')
    const sign_up_btn = document.querySelector('#sign-up-btn')
    const container = document.querySelector('.container')

    sign_up_btn.addEventListener('click', () => {
      container.classList.add('sign-up-mode')
    })

    sign_in_btn.addEventListener('click', () => {
      container.classList.remove('sign-up-mode')
    })
    this.changeCodeImg()
  },
  methods: {
    /**
     * @description: 获取验证码
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    getVerify() {
      // 验证手机号
      if (this.checkPhone() === false) {
        return false
      } else {
        axios.get('/code/sms', {
          params: {
            mobile: this.phoneForm.phone
          }
        })
          .then(res => {
            // console.log(res.data.msg)
          })
          .catch(() => {
            alert('发送失败')
          })

        const TIME_COUNT = 60 // 更改倒计时时间
        if (!this.timer) {
          this.count = TIME_COUNT
          this.show = false
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            } else {
              this.show = true
              clearInterval(this.timer) // 清除定时器
              this.timer = null
            }
          }, 1000)
        }
      }
    },

    /**
     * @description: 手机号验证
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    checkPhone() {
      const phone = this.phoneForm.phone
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        this.$message.error('请填写正确的手机号')
        return false
      }
    },

    /**
     * @description: 修改密码
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    retrievePassword() {
      axios.post('user/retrievePassword', {
        mobile: this.phoneForm.phone,
        password: this.phoneForm.psw,
        smsCode: this.phoneForm.phverify
      })
        .then(res => {
          // console.log(res)
          if (res.data.code === 200) {
            this.dialogVisible = false
            this.$message.success('修改密码成功')
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch(err => {
          console.error(err)
          this.$message.error('修改密码失败')
        })
    },

    /**
     * @description: 注册
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    register() {
      var select = document.getElementById('userrole')
      var value = select.value
      var rule = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

      var f = 0
      const usernumber = this.registerForm.usernumber
      if (!(/^[A-Za-z0-9]+$/.test(usernumber))) {
        f = 1
        this.$notify({
          title: '错误',
          message: '学号或工号只能为数字或英文，且不能为空',
          typr: 'error',
          position: 'top-left'
        })
      } else if (this.registerForm.username === '') {
        f = 1
        this.$notify({
          title: '错误',
          message: '用户名不为空',
          typr: 'error',
          position: 'top-left'
        })
      } else if (!(/^[\u4e00-\u9fa5]{0,5}$/.test(this.registerForm.realname))) {
        f = 1
        this.$notify({
          title: '错误',
          message: '真实姓名只能为1-5位中文',
          typr: 'error',
          position: 'top-left'
        })
      } else if (!(/^1[3456789]\d{9}$/.test(this.registerForm.mobile))) {
        f = 1
        this.$notify({
          title: '错误',
          message: '手机号格式不正确',
          typr: 'error',
          position: 'top-left'
        })
      } else if (!(rule.test(this.registerForm.email))) {
        f = 1
        this.$notify({
          title: '错误',
          message: '邮箱格式不正确',
          typr: 'error',
          position: 'top-left'
        })
      } else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/.test(this.registerForm.password)) {
        f = 1
        this.$notify({
          title: '错误',
          message: '密码长度要大于6位，由数字和字母组成',
          typr: 'error',
          position: 'top-left'
        })
      } else if (!f) {
        axios
          .post('/user/register', {
            userEmail: this.registerForm.email,
            userMobile: this.registerForm.mobile,
            userRealname: this.registerForm.realname,
            password: this.registerForm.password,
            username: this.registerForm.username,
            userNumber: this.registerForm.usernumber,
            roleId: value
          })
          .then(() => {
            this.$message.success('注册成功')
            this.registerForm.email = ''
            this.registerForm.mobile = ''
            this.registerForm.password = ''
            this.registerForm.username = ''
            this.registerForm.usernumber = ''
            this.registerForm.realname = ''
          })
          .catch((err) => {
            alert(err.msg)
          })
      }
    },

    /**
     * @description: 更改图形验证码
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    changeCodeImg() {
      axios
        .get('/code/image', {
          responseType: 'arraybuffer'
        })
        .then((res) => {
          // 将从后台获取的图片流进行转换
          return (
            'data:image/png;base64,' +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ''
              )
            )
          )
        })
        .then((res2) => {
          // 接收转换后的Base64图片
          this.pswverifyimg = res2
        })
        .catch(() => {})
    },

    /**
     * @description: 登录
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    userpwdLogin() {
      axios
        .post('/user/login', {
          username: crypto.set(this.loginForm.username),
          password: crypto.set(this.loginForm.password),
          // username: this.loginForm.username,
          // password: this.loginForm.password,
          // 加密
          // password: crypto.set(this.loginForm.password),
          imageCode: this.loginForm.pswverify
        })
        .then((res) => {
          // console.log('login', res)
          if (res.data.code === 406) {
            this.$message.info('111', res)
            this.changeCodeImg()
          } else {
            var s
            window.sessionStorage.clear()
            this.$store.commit('setToken', res.data.Token)
            // console.log(this.$store.state.token);
            // window.sessionStorage.setItem("token", res.data.Token);
            this.roleName = res.data.roleName
            this.permissionList = res.data.permissionList
            this.$store.commit('setpermissionList', JSON.stringify(this.permissionList))
            this.$store.commit('setroleName', this.roleName)
            this.$store.commit('setuserId', res.data.data.userId)
            s = crypto.set(res.data.data.username)
            this.$store.commit('setusername', s)

            s = crypto.set(res.data.data.userEmail)
            this.$store.commit('setuserEmail', s)

            s = crypto.set(res.data.data.userMobile)
            this.$store.commit('setuserMobile', s)

            s = crypto.set(res.data.data.userNumber)
            this.$store.commit('setuserNumber', s)

            this.$store.commit('setnewuser', res.data.data.userStatus)
            // console.log('111', this.$store.getters.getnewuser)
            this.$router.push({ path: `/home/${this.roleName}`, params: { data: this.permissionList, key: this.roleName }})
          }
        })
        .catch((err) => {
          if (err.response.data.msg === 'Bad credentials') {
            this.$message.error('账户名或密码错误')
          } else {
            this.$message.error('验证码错误')
          }
          this.changeCodeImg()
          // console.log('login', err.response.data.msg)
        })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/* google字体库 */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
input {
  font-family: "Poppins", sans-serif;
}
.phonein{
  .el-form-item{
    margin-bottom: 20px;
  }
  .loginbtn{
    width: 200px;
    height: 40px;
  }
}
.verifybtn{
  width:100px;
  height: 40px;
  position:absolute;
  right:0px;
  top:0
}
.container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
  overflow: hidden;
}

.container::before {
  content: "";
  position: absolute;
  width: 2000px;
  height: 2000px;
  border-radius: 50%;
  background: linear-gradient(-45deg, #4481eb, #04befe);
  top: -10%;
  right: 48%;
  transform: translateY(-50%);
  z-index: 6;
  transition: 1.8s ease-in-out;
}

.forms-container {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.signin-signup {
  position: absolute;
  top: 50%;
  left: 75%;
  /* 作用是什么 */
  transform: translate(-50%, -50%);
  width: 50%;
  display: grid;
  grid-template-columns: 1fr;
  z-index: 5;
  transition: 1s 0.7s ease-in-out;
}

form {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 0 5rem;
  overflow: hidden;
  /* 难点 */
  grid-column: 1 / 2;
  grid-row: 1 / 2;

  /* delay防止表单提前暴露 */
  transition: 0.2s 0.7s ease-in-out;
}

form.sign-in-form {
  z-index: 2;
}

form.sign-up-form {
  z-index: 1;
  opacity: 0;
}

.title {
  font-size: 2.2rem;
  color: #444;
  margin-bottom: 10px;
}

.input-field {
  max-width: 300px;
  width: 100%;
  height: 55px;
  background-color: #f0f0f0;
  margin: 10px 0;
  border-radius: 55px;
  display: grid;
  grid-template-columns: 15% 85%;
  padding: 0 0.4rem;
}

.input-verify {
  max-width: 150px !important;
  width: 80% !important;
  position: relative;
  left: -70px;
  input {
    margin-top: 13px;
  }
}
.input-verify a {
  position: relative;
  right: -180px;
  top: -32px;
  width: 100px;
  height: 40px;
  img {
    width: 100%;
    height: 100%;
  }
}

.input-field i {
  text-align: center;
  line-height: 55px;
  color: #acacac;
  font-size: 1.1rem;
}

.input-field input {
  background: none;
  outline: none;
  border: none;
  line-height: 1;
  font-weight: 600;
  font-size: 1.1rem;
  color: #333;
}
.input-field select {
  background: none;
  outline: none;
  border: none;
  line-height: 1;
  font-weight: 600;
  font-size: 1.1rem;
  width: 220px;
  color: #333;
}

.input-field input::placeholder {
  color: #aaa;
  font-weight: 500;
}

.btn {
  width: 150px;
  height: 40px;
  border: none;
  outline: none;
  border-radius: 49px;
  cursor: pointer;
  background-color: #5995fd;
  color: #fff;
  /* 大写 */
  text-transform: uppercase;
  font-weight: 600;
  margin: 10xp 0;
  /* 动画延迟 */
  transition: 0.5s;
}

.btn:hover {
  background-color: #4d84e2;
}

.social-text {
  padding: 0.7rem 0;
  font-size: 1rem;
}

.social-media {
  display: flex;
  justify-content: center;
}

.social-icon {
  height: 40px;
  width: 40px;
  border: 1px solid #333;
  margin: 0 0.45rem;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  color: #333;
  font-size: 1.1rem;
  border-radius: 50%;
  transition: 0.3s;
}

.social-icon:hover {
  color: #4481eb;
  border-color: #44b1eb;
}

.panels-container {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.panel {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  text-align: center;
  justify-content: center;
  z-index: 7;
}

.panel .content {
  color: #fff;
  transition: 0.9s 0.6s ease-in-out;
}

.panel h3 {
  font-weight: 600;
  line-height: 1;
  font-size: 1.5rem;
}

.panel p {
  font-size: 0.95rem;
  padding: 0.7rem 0;
}

.btn.transparent {
  margin: 0;
  background: none;
  border: 2px solid #fff;
  width: 130px;
  height: 41px;
  font-weight: 600;
  font-size: 0.8rem;
}

.left-panel {
  pointer-events: all;
  padding: 3rem 17% 2rem 12%;
}

.right-panel {
  pointer-events: none;
  padding: 3rem 12% 2rem 17%;
}

.image {
  width: 100%;
  transition: 1.1s 0.4s ease-in-out;
}

.right-panel .content,
.right-panel .image {
  transform: translateX(800px);
}

.container.sign-up-mode:before {
  transform: translate(100%, -50%);
  right: 52%;
}

.container.sign-up-mode .left-panel .image,
.container.sign-up-mode .left-panel .content {
  transform: translateX(-800px);
}

.container.sign-up-mode .right-panel .content,
.container.sign-up-mode .right-panel .image {
  transform: translateX(0px);
}

.container.sign-up-mode .left-panel {
  pointer-events: none;
}

.container.sign-up-mode .right-panel {
  pointer-events: all;
}

.container.sign-up-mode .signin-signup {
  left: 25%;
}

.container.sign-up-mode form.sign-in-form {
  z-index: 1;
  opacity: 0;
}

.container.sign-up-mode form.sign-up-form {
  z-index: 2;
  opacity: 1;
}

@media (max-width: 870px) {
  .container {
    min-height: 800px;
    height: 100vh;
  }

  .container:before {
    width: 1500px;
    height: 1500px;
    left: 30%;
    bottom: 68%;
    transform: translateX(-50%);
    right: initial;
    top: initial;
    transition: 2s ease-in-out;
  }

  .signin-signup {
    width: 100%;
    left: 50%;
    top: 85%;
    transform: translate(-50%, -100%);
    transition: 1s 0.8s ease-in-out;
  }

  .panels-container {
    z-index: 10;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr 2fr 1fr;
  }

  .panel {
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    padding: 2.5rem 8%;
  }

  .image {
    width: 200px;
    transition: 0.9s 0.6s ease-in-out;
  }

  .left-panel {
    grid-row: 1 / 2;
  }

  .right-panel {
    grid-row: 3 / 4;
  }

  .panel h3 {
    font-size: 1.2rem;
  }

  .panel p {
    font-size: 0.7rem;
    padding: 0.5rem 0;
  }

  .btn.btn.transparent {
    width: 110px;
    height: 35px;
    font-variation-settings: 0.7rem;
  }

  .panel .content {
    padding-right: 15%;
    transition: 0.9s 0.8s ease-in-out;
  }

  .right-panel .content,
  .right-panel .image {
    transform: translateY(300px);
  }

  .container.sign-up-mode:before {
    transform: translate(-50%, 100%);
    bottom: 32%;
    right: initial;
  }

  .container.sign-up-mode .left-panel .image,
  .container.sign-up-mode .left-panel .content {
    transform: translateY(-300px);
  }

  .container.sign-up-mode .signin-signup {
    top: 5%;
    transform: translate(-50%, 0);
    left: 50%;
  }
}

@media (max-width: 465px) {
  form {
    padding: 0 1.5rem;
  }

  .image {
    display: none;
  }

  .container .left-panel .content,
  .container .right-panel .content {
    margin-left: 40px;
  }
}
</style>
